package com.fsnmt.maizhuanbao.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;

/**
 * CacheManager.getInstance().getCache;
 */
public class CacheManager {
	private static CacheManager instance;
	public static Context mContext;
	private static ACache aCache;
	private static File listFile,apkFile,imageFile,pickFile;
	private static String commonCache,userCache;
	private String KEY_NONE = "none";
	private Properties pt;
	private CacheManager() {
		getCommonDir();//获取公共目录
		initMapFile();//初始化映射表
	}

	public static void init(Context context){
		mContext = context;
		listFile=null;
		apkFile=null;
		imageFile=null;
		pickFile=null;
		commonCache= null;
		userCache = null;
		aCache = null;
		instance = null;
	}

	static public void clear() {
		instance = null;
	}

	static  public CacheManager getInstance(){
		if(null == instance){
			synchronized (CacheManager.class){
				if(null==instance){
					instance = new CacheManager();
				}
			}
		}
		return instance;
	}

	/**
	 * 判断是否存在外部存储
	 * @return
	 */
	private boolean isSDCARDMounted() {
		String status = Environment.getExternalStorageState();
		return status.equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * 根据id 绑定 用户的缓存，缓存文件名为公共目录下的name
	 * @param id
	 * @param name
	 */
	public void bindUserCache(String id,String name){
		if(TextUtils.isEmpty(id) || TextUtils.isEmpty(name)){
			 throw  new IllegalStateException("bindUserCache id or name is null");
		}
		if(null==pt.getProperty(id)){
			pt.setProperty(id,name);
			saveMapFile();
			userCache = getCommonDir()+File.separator+name;
		}else {
			userCache = getCommonDir() + File.separator + pt.getProperty(id);
		}
		new File(userCache).mkdir();
	}

	/**
	 * 根据id 绑定 用户的缓存，缓存文件名为公共目录下的时间标志
	 * @param id
	 */
	public void bindUserCache(String id){
		if(TextUtils.isEmpty(id)){
			throw  new IllegalStateException("bindUserCache id is null");
		}
		String name = null;
		if(null!=pt.getProperty(id)){
			name = pt.getProperty(id);
		}else{
			name = pt.getProperty(KEY_NONE);
			pt.remove(KEY_NONE);
			pt.setProperty(id, name);
			String temp = String.valueOf(System.currentTimeMillis());
			new File(getCommonDir()+File.separator+temp).mkdir();
			pt.setProperty(KEY_NONE, temp);
			saveMapFile();
		}
		userCache = getCommonDir()+File.separator+name;
		new File(userCache).mkdir();
	}

	public void removeUserCache(String id){
		if(null!=pt.getProperty(id)){
			String temp =pt.getProperty(id);
			pt.remove(id);
			FileUtils.deleteAllFilesAndDir(getCommonDir() + File.separator + temp);
			saveMapFile();
		}
	}

	/**
	 * 清楚所有用户缓存进入无主状态
	 */
	public void removeAllUserCache(){
		Enumeration enum1 = pt.propertyNames();//得到配置文件的名字
		ArrayList<String> keys = new ArrayList<String>();
		while(enum1.hasMoreElements()) {
			String strKey = (String) enum1.nextElement();
			if(KEY_NONE.equals(strKey))
				continue;
			String strValue = pt.getProperty(strKey);
			FileUtils.deleteAllFilesAndDir(getCommonDir() + File.separator + strValue);
			keys.add(strKey);
		}
		if(0<keys.size()){
			for (String key : keys){
				pt.remove(key);
			}
			saveMapFile();
		}
		reset();
	}

	/**
	 * 无主状态
	 */
	public void reset(){
		String temp = null;
		if(null==pt.getProperty(KEY_NONE)){
			temp = String.valueOf(System.currentTimeMillis());
			pt.setProperty(KEY_NONE, temp);
			saveMapFile();
			userCache = getCommonDir()+File.separator+temp;
		}else{
			temp = pt.getProperty(KEY_NONE);
			userCache = getCommonDir()+File.separator+temp;
		}
		new File(userCache).mkdir();
		aCache = null;
	}

	private void saveMapFile(){
		File f = new File(getCommonDir()+File.separator+"setting.txt");
		if(!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			pt.store(new FileOutputStream(f), "配置文件");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void initMapFile(){
		pt = getMapFile();
		String temp = null;
		if(null==pt.getProperty(KEY_NONE)){
			temp = String.valueOf(System.currentTimeMillis());
			pt.setProperty(KEY_NONE, temp);
			saveMapFile();
			userCache = getCommonDir()+File.separator+temp;
		}else{
			temp = pt.getProperty(KEY_NONE);
			userCache = getCommonDir()+File.separator+temp;
		}
		new File(userCache).mkdir();
	}

	private Properties getMapFile(){
		File f = new File(getCommonDir()+File.separator+"setting.txt");
		if(!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Properties pt=new Properties();
		try {
			pt.load(new FileInputStream(f));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return pt;
	}

	private String getCommonDir(){
		if(TextUtils.isEmpty(commonCache)) {
			if (isSDCARDMounted() && SystemUtils.checkStoragePermission(mContext)) {
				commonCache = Environment.getExternalStorageDirectory() + File.separator + folder.dirName;
			}else{
				commonCache = mContext.getFilesDir() + File.separator + folder.dirName;
			}
			File cacheFile = new File(commonCache);
			if(!cacheFile.exists()){
				boolean mkdir = cacheFile.mkdir();//有个别手机api显示挂载了外存但是实际没有
				if(!mkdir){
					commonCache = mContext.getFilesDir() + File.separator + folder.dirName;
					cacheFile = new File(commonCache);
					if(!cacheFile.exists()){
						mkdir = cacheFile.mkdir();
					}
				}
			}
		}
		return commonCache;
	}

	public String getUserDir(){
		return userCache;
	}

	public ACache getCache() {
		if(null==aCache ) {
			listFile = new File(userCache, folder.listName);
			if (!listFile.exists() && !listFile.mkdirs()) {
				boolean storagePermission = SystemUtils.checkStoragePermission(mContext);
			}
			aCache = ACache.get(listFile);
		}
		return aCache;
	}

	public String getApkFolder(){
		apkFile = new File(userCache, folder.apkName);
		apkFile.getParentFile().mkdirs();
		if(!apkFile.exists()){
			apkFile.mkdir();
		}
		return userCache +File.separator+ folder.apkName;
	}

	public String getImagesFolder(){
		imageFile = new File(userCache, folder.imageName);
		imageFile.getParentFile().mkdirs();
		if (!imageFile.exists()) {
				imageFile.mkdir();
		}
		return userCache +File.separator+ folder.imageName;
	}

	public String getPickFolder(){
		pickFile = new File(userCache, folder.pickName);
		pickFile.getParentFile().mkdirs();
		if (!pickFile.exists()) {
			pickFile.mkdir();
		}
		return userCache +File.separator+ folder.pickName;
	}

	public void clearCache(){
		if(null!=listFile && listFile.exists())
			FileUtils.deleteAllFiles(listFile);
		if(null!=apkFile && apkFile.exists())
			FileUtils.deleteAllFiles(apkFile);
		if(null!=imageFile && imageFile.exists())
			FileUtils.deleteAllFiles(imageFile);
		if(null!=pickFile && pickFile.exists())
			FileUtils.deleteAllFiles(pickFile);
	}


	public interface folder{
		 String dirName = "mzb_lib";
		 String apkName = "apks";
		 String imageName = "images";
		 String pickName = "pick";
		 String listName = "lists";
	}

}
